<template>
  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <span><i class="el-icon-document-add"></i> 护士站 - 入院申请列表</span>
      </div>
    </template>

    <el-form :inline="true" :model="searchForm" @submit.prevent="handleSearch">
      <el-form-item label="病人姓名">
        <el-input v-model="searchForm.patientName" placeholder="输入病人姓名"></el-input>
      </el-form-item>
      <el-form-item label="申请日期">
        <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="tableData" v-loading="loading" style="width: 100%">
      <el-table-column prop="id" label="申请ID" width="80" />
      <el-table-column prop="patientName" label="病人姓名" width="120" />
      <el-table-column prop="doctorName" label="申请医生" width="120" />
      <el-table-column prop="departmentName" label="申请科室" width="150" />
      <el-table-column prop="iaDate" label="申请日期" width="180" />
      <el-table-column prop="status" label="状态" width="120">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ formatStatus(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" min-width="150">
        <template #default="scope">
          <el-button
              v-if="scope.row.status == 0"
              size="small"
              type="primary"
              @click="handleAdmission(scope.row)"
          >
            办理入院
          </el-button>
          <el-button
              v-if="scope.row.status == 0"
              size="small"
              type="danger"
              @click="handleReject(scope.row)"
          >
            拒绝
          </el-button>
          <span v-else>—</span>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
        style="margin-top: 20px;"
        v-model:current-page="pagination.pageNum"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
    />
  </el-card>

  <el-dialog v-model="dialogVisible" title="办理入院手续" width="50%">
    <el-form :model="admissionForm" ref="admissionFormRef" label-width="100px">
      <el-form-item label="病人姓名">
        <el-input v-model="currentApplication.patientName" disabled></el-input>
      </el-form-item>
      <el-form-item label="申请科室">
        <el-input v-model="currentApplication.departmentName" disabled></el-input>
      </el-form-item>

      <el-form-item label="主治医生" prop="doctorId" :rules="[{ required: true, message: '请选择主治医生', trigger: 'change' }]">
        <el-select v-model="admissionForm.doctorId" placeholder="请选择主治医生" style="width: 100%;">
          <el-option
              v-for="doctor in doctorOptions"
              :key="doctor.id"
              :label="doctor.name"
              :value="doctor.id"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="安排病床" prop="bedId" :rules="[{ required: true, message: '请选择空病床', trigger: 'change' }]">
        <el-select v-model="admissionForm.bedId" placeholder="请选择空病床" style="width: 100%;">
          <el-option
              v-for="bed in bedOptions"
              :key="bed.id"
              :label="`${bed.wardNo} - ${bed.bedNo}`"
              :value="bed.id"
          ></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitAdmission">确认办理</el-button>
    </template>
  </el-dialog>

</template>

<script>
// 引入 Element Plus 的消息提示
import { ElMessage, ElMessageBox } from 'element-plus';
import {queryAllApply} from "../api/inpatient.js";
import { loadAdmissionResources, processAdmission } from "../api/admission.js";
import {rejectAdmission} from "../api/admission.js";

// --- Vue 组件定义 ---
export default {
  name: "InpatientApplicationList",
  // 1. data() 选项
  data() {
    return {
      // 搜索表单
      searchForm: {
        patientName: '',
        dateRange: [] // [startDate, endDate]
      },
      // 表格数据
      tableData: [],
      loading: false,
      // 分页
      pagination: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },

      // --- 办理入院弹窗 ---
      dialogVisible: false,
      currentApplication: {}, // 当前正在操作的申请行
      admissionForm: {
        doctorId: null,
        bedId: null
      },
      doctorOptions: [], // 可选医生列表
      bedOptions: [] // 可选病床列表
    };
  },

  // 2. methods 选项
  methods: {
    // 获取主列表数据
    async fetchData() {
      const query = {
        pageNum: this.pagination.pageNum,
        pageSize: this.pagination.pageSize,
        patientName: this.searchForm.patientName,
        applicationStartDate: this.searchForm.dateRange ? this.searchForm.dateRange[0] : null,
        applicationEndDate: this.searchForm.dateRange ? this.searchForm.dateRange[1] : null,
      };

      // 对应我们之前设计的 POST /inpatient-app/list 接口
      let {data:data} = await queryAllApply(query)
      console.log(data)
      if (data.code == 400){
        ElMessage.warning("未搜索到结果")
        this.tableData = null
      }else {
        this.tableData = data.obj.list;
      }
      this.pagination.total = data.obj.total;
    },

    // 搜索
    handleSearch() {
      this.pagination.pageNum = 1; // 搜索时重置回第一页
      this.fetchData();
    },

    // 重置搜索
    handleReset() {
      this.searchForm.patientName = '';
      this.searchForm.dateRange = [];
      this.handleSearch();
    },

    // 分页：每页条数变化
    handleSizeChange(val) {
      this.pagination.pageSize = val;
      this.fetchData();
    },

    // 分页：当前页码变化
    handlePageChange(val) {
      this.pagination.pageNum = val;
      this.fetchData();
    },

    // 格式化状态显示
    formatStatus(status) {
      // 对应 'inpatient_application' 表的 'ia_status' 字段
      if (status == "0") return '待确定'; // 待护士办理入院
      if (status == "1") return '待缴费'; // 待用户去收银台缴费
      if (status == "2") return '已完成'; // 已办理入院
      if (status == "3") return '已拒绝';
      return '未知';
    },

    // 状态标签样式
    getStatusType(status) {
      if (status == "0") return 'danger'; // (需求更改，先审核后缴费)
      if (status == "1") return 'warning'; // 待缴费
      if (status == "2") return 'success'; // 已完成
      if (status == "3") return 'danger';
      return 'info';
    },

    // --- 核心操作方法 (对应需求文档) ---

    // 1. 点击"办理入院"
    async handleAdmission(row) {
      if (!row.patientId || !row.departmentId) {
        ElMessage.error("数据错误：该申请缺少 patientId 或 departmentId，请联系管理员检查后端 queryAllApply API。");
        return;
      }
      this.currentApplication = { ...row };

      // 重置表单
      this.admissionForm.doctorId = null;
      this.admissionForm.bedId = null;
      if (this.$refs.admissionFormRef) {
        this.$refs.admissionFormRef.clearValidate();
      }

      // *** 4. 调用真实的 API (替换 mock) ***
      try {
        const { data: response } = await loadAdmissionResources(row.departmentId);
        if (response.code === 200) {
          this.doctorOptions = response.obj.doctors;
          this.bedOptions = response.obj.beds;
        } else {
          ElMessage.error(response.message || "加载医生或床位失败");
        }
      } catch (err) {
        ElMessage.error("加载资源失败，请检查网络");
      }

      this.dialogVisible = true;
    },

    // 2. 提交入院
    submitAdmission() {
      // 表单验证
      this.$refs.admissionFormRef.validate(async (valid) => {
        if (valid) {

          // 构造 DTO
          const requestData = {
            applicationId: this.currentApplication.id,
            patientId: this.currentApplication.patientId, // (来自前提)
            departmentId: this.currentApplication.departmentId, // (来自前提)
            doctorId: this.admissionForm.doctorId,
            bedId: this.admissionForm.bedId
          };

          try {
            // *** 6. 调用真实的 API (替换 mock) ***
            const { data: response } = await processAdmission(requestData);

            if(response.code === 200) {
              ElMessage.success('办理入院成功!');
              this.dialogVisible = false;
              await this.fetchData(); // 刷新列表
            } else {
              ElMessage.error(response.message || '办理入院失败');
            }
          } catch (err) {
            ElMessage.error(err.message || '办理入院失败');
          }
        } else {
          ElMessage.warning('请选择主治医生和病床');
          return false;
        }
      });
    },

    // 3. 拒绝申请
    handleReject(row) {
      // (前提：您的 listInpatientApps 必须返回 doctorId 和 patientId)
      if (!row.patientId || !row.doctorId) {
        ElMessage.error("数据错误：缺少 DoctorId 或 PatientId，无法发送通知。");
        return;
      }

      // 弹出输入框，要求护士填写拒绝理由
      ElMessageBox.prompt('请输入拒绝理由：', '拒绝入院申请', {
        confirmButtonText: '确认拒绝',
        cancelButtonText: '取消',
        inputType: 'textarea',
        inputValidator: (value) => {
          if (!value || value.trim() === '') {
            return '拒绝理由不能为空';
          }
          return true;
        }
      }).then(async ({ value }) => {
        // (用户点击了确认)
        const requestData = {
          applicationId: row.id,
          doctorId: row.doctorId,     // (来自 queryAllApply 返回的 ia_workerid)
          patientId: row.patientId,    // (来自 queryAllApply 返回的 ia_caseid)
          reason: value
        };

        try {
          const { data: response } = await rejectAdmission(requestData);
          if (response.code === 200) {
            ElMessage.success('申请已拒绝，并已通知医生');
            this.fetchData(); // 刷新列表
          } else {
            ElMessage.error(response.message || '操作失败');
          }
        } catch (err) {
          ElMessage.error(err.response?.data?.message || '操作失败');
        }

      }).catch(() => {
        // (用户点击了取消)
      });
    }
  },

  // 3. created() 钩子
  created() {
    // 页面加载时自动获取第一页数据
    this.fetchData();
  }
};
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: 600;
}
.el-form {
  border-bottom: 1px solid var(--el-border-color-light);
  padding-bottom: 10px;
  margin-bottom: 20px;
}
</style>